<?php


namespace tmcore\services;

use app\common\model\log\QueueLog;

class QueueService
{
    /**
     * 添加队列日志
     * @param $data
     * @return boolean
     */
    public function addQueueLog($data) {

        if(empty($data['job_id'])) return false;

        $row = QueueLog::where(['job_id' => $data['job_id']])->field('id,job_id,backup')->findOrEmpty()->toArray();

        if(!$row) {
            $create_data = [
                'queue' => $data['queue'],
                'job' => $data['job'],
                'job_name' => $data['job_name'],
                'job_id' => $data['job_id'],
                'result' => $data['result']??0,
                'result_msg' => $data['result_msg'],
                'param' => $data['param'],
                'drive' => $data['drive'],
                'execute_time' => $data['execute_time']??0,
                'retry_num' => $data['retry_num'],
                'backup' => $this->getBackup('',$data),
            ];
            $res = QueueLog::create($create_data);
            return $res?true:false;
        } else {
            $update_data = [
                'result' => $data['result']??0,
                'result_msg' => $data['result_msg'],
                'param' => $data['param'],
                'execute_time' => $data['execute_time']??0,
                'retry_num' => $data['retry_num'],
                'backup' => $this->getBackup($row['backup'], $data),
                'update_time' => $data['notify_time']??time(),
            ];
            $res = QueueLog::where(['id' => $row['id']])->update($update_data);
            return $res !== false;
        }
    }

    /**
     * 获取备份参数
     * @param string $data 原数据
     * @param array $add 添加参数
     * @return string
     */
    private function getBackup($data, $add) {
        $backup = $data?json_decode($data, true):[];
        array_unshift($backup, $add);
        return json_encode($backup, 320);
    }
}